package com.httpclient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;

public class TestFubao {

    private static Map<String, String> urlDoctorMap = new HashMap<String, String>();

    static {
        urlDoctorMap.put("普通产科", "http://guahao.zjol.com.cn/DepartMent.Aspx?ID=3271");
        File topdir = new File("c:\\log\\log");
        if (!topdir.isDirectory()) {
            topdir.mkdirs();
        }
    }

    /**
     * 
     * @param client
     * @param userName
     * @param pwd
     * @return
     */
    public String login(HttpClient client, String userName, String pwd) {
        String result = "";
        int maxtry = 10;
        while (result.indexOf("OK") < 0) {
            if (maxtry-- < 0) {
                return "error";
            }
            GetMethod getFirst = new GetMethod("http://guahao.zjol.com.cn/VerifyCodeCH.aspx");
            try {
                if (HttpStatus.SC_OK == client.executeMethod(getFirst)) {
                    InputStream inputstream = getFirst.getResponseBodyAsStream();
                    BufferedInputStream bis = new BufferedInputStream(inputstream);
                    FileOutputStream fos = new FileOutputStream("c:\\log\\a.jpeg");
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    int read;
                    while ((read = bis.read()) != -1) {
                        bos.write(read);
                    }
                    bos.close();// 不关闭，输出流不刷新，有可能得到无效图片 o

                    client.getState().addCookies(client.getState().getCookies());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                getFirst.releaseConnection();
            }

            String url = "http://guahao.zjol.com.cn/ashx/LoginDefault.ashx?idcode=" + userName + "&pwd=" + pwd
                    + "&txtVerifyCode=";

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String str = null;
            System.out.println("Enter your VerifyCode:");
            try {
                str = br.readLine();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            url = url + str;
            System.out.println("your url is :" + url + str);
            GetMethod getMethod2 = new GetMethod(url);

            try {
                // getFirst.setRequestHeader("Cookie", cookies.toString());

                // 开始进行登录验证信息提交， 关键是注意参数的顺序
                if (HttpStatus.SC_OK == client.executeMethod(getMethod2)) {

                    client.getState().addCookies(client.getState().getCookies());
                    result = getResponseBody(getMethod2.getResponseBodyAsStream(), "UTF-8");
                    getMethod2.releaseConnection();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                getMethod2.releaseConnection();
            }
        }
        return result;
    }

    /**
     * 获取预订的医生的信息。
     * 注意由于是在下午3点放票。所以。。。
     * @param client
     * @param doctorUrl
     * @return
     */
    public String getDoctorCodeInfo(HttpClient client, String doctorUrl) {
        GetMethod getFirst = new GetMethod(doctorUrl);
        String code = "";
        int dd = 5;

        while (dd-- > 0) {

            try {
                System.out.println("dddddddddddddddddddddd" + dd + ",time"
                        + Calendar.getInstance().getTime().toLocaleString());

                System.err.println("ddddddddddddddddddddddddddddddddddddddddd" + dd + ",time"
                        + Calendar.getInstance().getTime().toLocaleString());;
                Calendar cal = Calendar.getInstance();

                boolean open = false;
                if (open) {
                    if ((cal.get(Calendar.HOUR_OF_DAY) == 14)) {
                        int min = cal.get(Calendar.MINUTE);
                        if (min < 50) {
                            Thread.sleep(1000 * 60 * 5);
                        } else if (min < 57) {
                            Thread.sleep(1000 * 30);
                        } else if (min < 59) {
                            Thread.sleep(1000 * 5);
                        } else {
                            // 从59分开始，开始暴力尝试。
                        }

                    } else if ((cal.get(Calendar.HOUR_OF_DAY) == 15)) {
                        int min = cal.get(Calendar.MINUTE);
                        if (min < 5) {
                            // 前两分钟暴力尝试。
                        } else {
                            Thread.sleep(1000 * 60 * 5);
                        }

                    } else {
                        Thread.sleep(1000 * 60 * 5);
                    }
                }
                client.executeMethod(getFirst);
                String result = getResponseBody(getFirst.getResponseBodyAsStream(), "UTF-8");
                getFirst.releaseConnection();
                Parser parser = new Parser(result);
                parser.setInputHTML(result);
                NodeFilter tableFilter = new NodeClassFilter(TableTag.class);
                NodeList tableList = parser.extractAllNodesThatMatch(tableFilter);
                for (int i = 0; i < tableList.size(); i++) {
                    TableTag table = (TableTag) tableList.elementAt(i);
                    // 取得表中的行集
                    TableRow[] rows = table.getRows();
                    // 遍历每行
                    for (int r = 0; r < rows.length; r++) {
                        TableRow tr = rows[r];
                        TableColumn[] td = tr.getColumns();
                        // 行中的列
                        for (int c = 0; c < td.length; c++) {
                            String str = td[c].toHtml();
                            String[] ss = str.split("'");
                            if (ss.length > 2) {
                                for (int pp = 0; pp < ss.length - 1; pp++) {
                                    if (ss[pp].indexOf("showDiv") >= 0) {
                                        code = ss[pp + 1];
                                        System.out.println(dd + "==" + code);
                                        // return code;
                                    }
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("===========end");
        return code;
    }

    public Map<String, String> generateBookForm(HttpClient client, String code) {
        String url = "http://guahao.zjol.com.cn/ashx/gethy.ashx";
        PostMethod method = new PostMethod(url);
        method.addParameter("sg", code);
        Map<String, String> paramMap = new HashMap<String, String>();
        try {
            if (HttpStatus.SC_OK == client.executeMethod(method)) {
                String str = getResponseBody(method.getResponseBodyAsStream(), "UTF-8");
                int begin = str.lastIndexOf("$");
                if (begin > 0) {
                    str = str.substring(begin + 1, str.length());
                    String[] ss = str.split("\\||#");
                    paramMap.put("hyid", ss[0]);
                    paramMap.put("xh", ss[1]);
                    paramMap.put("qhsj", ss[2]);
                    paramMap.put("sg", ss[3]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return paramMap;
    }

    public String submitBookForm(HttpClient client, Map<String, String> paramMap) {
        String url = "http://guahao.zjol.com.cn/ashx/TreadYuyue.ashx";
        if (paramMap.size() < 3) {
            return "error";
        }
        getSubmitFormCheckCode(client);
        for (int tryNum = 0; tryNum < 17; tryNum++) {
            PostMethod method = new PostMethod(url);
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                method.addParameter(entry.getKey(), entry.getValue());
            }
            method.addParameter("yzm", "" + tryNum % 17);// 数字加的验证码。

            try {
                if (HttpStatus.SC_OK == client.executeMethod(method)) {
                    String str = getResponseBody(method.getResponseBodyAsStream(), "UTF-8");
                    System.out.println("last result==tryNum" + tryNum + str);
                    if (str.length() > 50) {
                        return str;
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                method.releaseConnection();
            }

        }

        return "";

    }

    /**
     * @param client
     */
    protected void getSubmitFormCheckCode(HttpClient client) {
        GetMethod getFirst = new GetMethod("http://guahao.zjol.com.cn/VerifyCodeCH_SG.aspx");
        try {
            if (HttpStatus.SC_OK == client.executeMethod(getFirst)) {
                InputStream inputstream = getFirst.getResponseBodyAsStream();
                BufferedInputStream bis = new BufferedInputStream(inputstream);
                FileOutputStream fos = new FileOutputStream("c:\\log\\b.jpeg");
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int read;
                while ((read = bis.read()) != -1) {
                    bos.write(read);
                }
                bos.close();// 不关闭，输出流不刷新，有可能得到无效图片 o

                client.getState().addCookies(client.getState().getCookies());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getFirst.releaseConnection();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(1000 * 10000);
        // 设置读数据超时时间
        client.getHttpConnectionManager().getParams().setSoTimeout(1000 * 10000);
        // 获取连接的时间
        client.getParams().setConnectionManagerTimeout(1000 * 10000);
        try {
            TestFubao testFubao = new TestFubao();
            System.out.println("login:" + testFubao.login(client, "33032819740212493X", "qwe123"));

            // 获取徐启顺的信息

            String code = testFubao.getDoctorCodeInfo(client,
                    "http://guahao.zjol.com.cn/DoctorInfo.Aspx?DEPART=69&ID=437");
            Map<String, String> paramMap = testFubao.generateBookForm(client, code);

            testFubao.submitBookForm(client, paramMap);
        } catch (Exception e) {

        }

    }

    public static void requestInterceptor(HttpMethod method) {
        method.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;");
        method.setRequestHeader("Accept-Language", "zh-cn");
        method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        method.setRequestHeader("Accept-Charset", "UTF-8");
        method.setRequestHeader("Keep-Alive", "300");
        method.setRequestHeader("Connection", "Keep-Alive");// close
        method.setRequestHeader("Cache-Control", "no-cache");
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }

    private String getResponseBody(InputStream inputStream, String encode) throws IOException {
        int max_bytes = 4096;
        byte[] b = new byte[max_bytes];
        StringBuilder builder = new StringBuilder();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead = inputStream.read(b, 0, max_bytes);
        while (bytesRead != -1) {
            baos.write(b, 0, bytesRead);
            builder.append(new String(b, 0, bytesRead));
            bytesRead = inputStream.read(b, 0, max_bytes);
        }
        String content = baos.toString(encode);
        baos.close();
        return content;
    }

}
